package com.surelution.lansao.vo

import org.apache.http.client.HttpClient
import org.apache.http.impl.client.DefaultHttpClient

class HttpClientContainer {
	
	public static final String KEY = "HttpClientContainer"
	
	private HashSet<Vo> set = new HashSet<Vo>();

	public HttpClient findClient(String uuid) {
		long expend = 1000 * 60 * 30
		HttpClient client = null;
		long now = System.currentTimeMillis()
		set.each {vo->
			if(vo.uuid == uuid) {
				client = vo.client
				vo.expireAt = now + expend
			} else if(vo.expireAt < now) {
			//just to avoid too much client in memory
				set.remove(vo)
			}
		}
		if(client == null) {
			client = new DefaultHttpClient()
			def vo = new Vo()
			vo.uuid = uuid
			vo.client = client
			vo.expireAt = System.currentTimeMillis() + expend
			set.add(vo)
		}
		return client
	}
	
	private class Vo {
		String uuid
		HttpClient client
		long expireAt
		
		@Override
		public int hashCode() {
			return uuid.hashCode();
		}
		
		@Override
		public boolean equals(Object obj) {
			if(obj instanceof Vo) {
				return obj.uuid == uuid
			}
			return false;
		}
	} 
}
